<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>购物车案例</title>
</head>

<body>
    <div id="app" align="center">
        <table border="1px" width="50%" cellspacing="0">
            <tr align="center">
                <th>编号</th>
                <th>书籍名称</th>
                <th>出版日期</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>操作</th>
            </tr>
            <tr align="center" v-for="(elemet,index) in items">
                <td>{{index + 1}}</td>
                <td>{{elemet.name}}</td>
                <td>{{elemet.date}}</td>
                <td>￥{{elemet.price}}</td>
                <td><input :disabled="elemet.count === 1" type="button" value="-" @click="sub(index)">
                    <span> &nbsp;{{elemet.count}}&nbsp;</span>
                    <input type="button" value="+" @click="add(index)">
                </td>
                <td><button @click="delete_(index)">移除</button></td>
            </tr>
        </table>
        <div>
            <h1>总价格：￥<span v-text="sum_">{{sum_}}</span></h1>
        </div>
    </div>
</body>
<script>
    new Vue({
        el: "#app",
        data: {
            items: [{
                name: "《java编程思想》",
                date: "2020-9",
                price: "98.00",
                count: 1
            }, {
                name: "《数据分析与数据原理》",
                date: "2010-2",
                price: "39.00",
                count: 1
            }, {
                name: "《Hadoop权威指南》",
                date: "2019-10",
                price: "59.00",
                count: 1
            }, {
                name: "《代码大全》",
                date: "2018-8",
                price: "128.00",
                count: 1
            }],
            sum_: "324.00"
        },
        methods: {
            add(index) {
                this.items[index].count += 1;
                //计算总价格
                this.sum();
            },
            sub(index) {
                this.items[index].count -= 1
                this.sum();
            },
            sum() {
                var sum_count = 0;
                for (var i = 0; i < this.items.length; i++) {
                    sum_count += parseInt(this.items[i].price) * this.items[i].count;
                }
                this.sum_ = sum_count.toFixed(2);
            },
            delete_(index) {
                console.log(index);
                if(confirm("确定移除吗？")){
                    this.items.splice(index,1);
                    this.sum();
                }
            }
        }
    })
</script>

</html>